package com.cms.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.name.Rename;

import org.codehaus.jackson.type.TypeReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cms.common.kit.Crop;
import com.cms.common.kit.CropRename;
import com.cms.common.kit.FileKit;
import com.cms.common.kit.RequestKit;
import com.cms.common.kit.ResponseKit;
import com.cms.common.kit.StrKit;
import com.cms.common.util.pass.JsonUtil;
import com.cms.controller.BaseController;
import com.cms.model.UpConfig;
import com.cms.model.Uploader;


@Controller
@RequestMapping(value = "/admin/uploader")
public class UploaderController extends BaseController{

	private static final String LIST_PAGE="admin/upconfig/uploader_list";
	
	@RequestMapping(value = "/index")
	public String index(Map<String, Object> map,String page,HttpServletRequest request) {
		map.put("page", Uploader.dao.paginate(toInt(page, 1), 15));
		return LIST_PAGE;
	}
	
	@RequestMapping(value = "/delete")
	public @ResponseBody String delete(Map<String, Object> map,String ids,String page,HttpServletRequest request) {
		List<Uploader> find = Uploader.dao.find("select fileLinkAttr from s_upload where id in(?)", ids);
		File file=null;
		for (Uploader f : find) {
			file=new File(f.getStr("fileLinkAttr"));
			if(file.exists())file.delete();
		}
		return Uploader.dao.deleteByIds(ids)?ResponseKit.responseSuccess("操作成功!"):ResponseKit.responseError("操作失败！");
	}
	
	
	@RequestMapping(value = "/up")
	public @ResponseBody String up(Map<String, Object> map,@RequestParam(value = "fileData", required = true) MultipartFile fileData,String channel,String folder,HttpServletRequest request) {
		String return_path="";
		// 获取上传配置
		UpConfig config = UpConfig.dao.findByChannel(channel);
		if(config!=null){
			String uploadPath = "uploads/"+config.getStr("base_path")+'/'+folder+"/";
			if(StrKit.isBlank(folder)){
				uploadPath = "uploads/"+config.getStr("base_path")+"/";
			}
			FileKit.createFolders(FileKit.getWebRoot(), uploadPath);
			//判断文件类型
			if(!FileKit.allowFileType(config.getStr("allow_type"),fileData)){
				return ResponseKit.responseError("不允许上传此文件!");
			}
			//if(fileData.getSize()>)
			//判断上传文件大小
			String oriName=fileData.getOriginalFilename();
			String stuff=oriName.substring(oriName.lastIndexOf("."), oriName.length());
			String randName=System.currentTimeMillis()+stuff;//随机名称
			return_path=uploadPath+randName;
			String destFilePath=FileKit.getWebRoot()+uploadPath;
			File destFile = new File(new File(destFilePath),randName);
			try {
				FileKit.copyFile(fileData.getInputStream(), destFile);
				fileData.getInputStream().close();
				Uploader.dao.addFile(oriName, stuff, randName, destFilePath, fileData, RequestKit.getRemortIP(request), uploadPath, config.getInt("id"));
				//如果上传成功是否需要缩略图或者增加水印
				if(config.getInt("auto_crop")==1){
					//需要缩略图
					List<Crop> crops = JsonUtil.json2GenericObject(config.getStr("crop_size_json"),new TypeReference< List<Crop> >(){});
					for (Crop crop : crops) {
						crop(crop,destFile.getAbsolutePath());
					}
				}
				if(config.getInt("auto_mark")==1){//文字水印
					//markText(config.getStr("mask_text"),destFile.getAbsolutePath());
				}
				if(config.getInt("auto_mark")==2){//图片水印处理
					markPic(config.getStr("mask_temp"),destFile.getAbsolutePath());
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			return ResponseKit.responseError("没有获取到上传配置！");
		}
		
		
		return ResponseKit.responseSuccess(return_path);
	}

	/**
	 * 加水印
	 * @param text
	 * @param path
	 */
	private void markPic(String markPath, String path) {
		try {
			Thumbnails.of(path).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(FileKit.getWebRoot()+markPath)) , 0.5f).outputQuality(1.0f).toFiles(Rename.NO_CHANGE);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 裁剪
	 * @param crop
	 * @param destFile
	 */
	private void crop(Crop crop, String path) {
		try {
			Thumbnails.of(path).size(crop.getThumb_width(), crop.getThumb_height()).outputQuality(1.0).toFiles(new CropRename(crop.getThumb_marker()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
}
